package cn.wjssl.infrastructure.persistent.repository;

import cn.wjssl.domain.task.model.entity.TaskEntity;
import cn.wjssl.domain.task.repository.ITaskRepository;
import cn.wjssl.infrastructure.event.EventPublisher;
import cn.wjssl.infrastructure.persistent.dao.ITaskDao;
import cn.wjssl.infrastructure.persistent.po.TaskPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author：lxd
 * @Description
 * @Date：2025/2/26
 */

@Slf4j
@Repository
public class TaskRepository implements ITaskRepository {

    @Resource
    private ITaskDao taskDao;

    @Resource
    private EventPublisher eventPublisher;

    // 查询发送MQ失败和超时1分钟未发送的MQ limit 10
    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        List<TaskPO> taskPOS = taskDao.queryNoSendMessageTaskList();
        List<TaskEntity> taskEntities = new ArrayList<>(taskPOS.size());
        // 转换
        for (TaskPO taskPO : taskPOS) {
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(taskPO.getUserId());
            taskEntity.setTopic(taskPO.getTopic());
            taskEntity.setMessageId(taskPO.getMessageId());
            taskEntity.setMessage(taskPO.getMessage());
            taskEntities.add(taskEntity);
        }
        return taskEntities;
    }

    // 发送消息
    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    // mq发送成功, 更新task状态为Completed
    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        TaskPO taskPO = new TaskPO();
        taskPO.setUserId(userId);
        taskPO.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(taskPO);
    }

    // 发送失败, 更新task状态为fail
    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        TaskPO taskPO = new TaskPO();
        taskPO.setUserId(userId);
        taskPO.setMessageId(messageId);
        taskDao.updateTaskSendMessageFail(taskPO);
    }
}
